/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.device.modular.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import vip.xiaonuo.device.core.enums.Constants;
import vip.xiaonuo.device.core.enums.DeviceErrEnum;
import vip.xiaonuo.device.modular.entity.ApiLog;
import vip.xiaonuo.device.modular.entity.BizCabinetDoor;
import vip.xiaonuo.device.modular.entity.DevApiGoods;
import vip.xiaonuo.device.modular.mapper.CabinetDoorMapper;
import vip.xiaonuo.device.modular.mapper.DevApiGoodsMapper;
import vip.xiaonuo.device.modular.service.DevApiGoodsService;
import vip.xiaonuo.device.modular.service.DevApiLogService;
import vip.xiaonuo.device.vo.Result;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 设备api日志Service接口实现类
 *
 * @author levin
 * @date 2022/11/30 13:27
 **/
@Service("deviceInventoryService")
@Transactional
public class DeviceInventoryServiceImpl extends DeviceBaseService {

    @Override
    protected Integer getReqType() {
        return Constants.INVENTORY_P;
    }

    @Resource
    private DevApiGoodsMapper devApiGoodsMapper;

    @Resource
    private DevApiGoodsService devApiGoodsService;

    @Resource
    private DevApiLogService devApiLogService;

    @Resource
    private CabinetDoorMapper cabinetDoorMapper;

    @Override
    protected Result checkData(JSONObject param) {
        JSONArray cabCodeList = param.getJSONArray("data");
        if (cabCodeList == null) {
            return Result.fail("data信息缺失");
        }
        if (cabCodeList.size() == 0) {
            return Result.fail("data信息不存在");
        }
        return Result.ok();
    }

    @Override
    protected void handleLog(ApiLog log, JSONObject param) {
        log.setUserId(param.getString("operator"));
    }

    @Override
    protected void handleWithParentLog(ApiLog log, JSONObject params) {
        //手动盘库
        int reqType = Constants.INVENTORY;
        String operator = params.getString("operator");
        if (StringUtils.isBlank(operator)) {
            //自动盘库
            reqType = Constants.AUTOINVENTORY;
        }
        JSONArray cabCodeList = params.getJSONArray("data");
        for (Object item : cabCodeList) {
            JSONObject itemJson = JSONObject.parseObject(item.toString());
            String cabCode = itemJson.getString("cabinetcode");
            String doorCode = itemJson.getString("doorcode");
            List<String> rfids = itemJson.getObject("rfids", List.class);

            //获取柜门信息
            BizCabinetDoor cabinetDoor = cabinetDoorMapper.getInfoByCodes(cabCode, doorCode);

            //添加日志
            ApiLog apiLog = new ApiLog();
            apiLog.setParentId(log.getId());
            apiLog.setCabinetCode(cabCode);
            apiLog.setCabinetDoorCode(doorCode);
            apiLog.setReqType(reqType);
            apiLog.setRfids(String.join(",", rfids));
            apiLog.setReqJson(log.getReqJson());
            apiLog.setEventTime(log.getEventTime());
            apiLog.setUserId(operator);
            apiLog.setActCompTime(cabinetDoor.getActTime());
            //更新柜门动作时间
            int count = cabinetDoorMapper.updateActTime(cabinetDoor.getId(),log.getEventTime());
            if(count==0){
                log.setResulltType(DeviceErrEnum.REQ_ACT_TIMEOUT.getValue());
            }else{
                apiLog.setResulltType(DeviceErrEnum.SUCCESS.getValue());
            }
            devApiLogService.save(apiLog);

            //新增部分rfids
            List<String> newRfids = rfids;
            //获取柜子+柜门下的所有物品数据
            List<DevApiGoods> goodsList = devApiGoodsMapper.getGoodsSnapshot(cabCode, doorCode);
            for (DevApiGoods apiGoods : goodsList) {
                apiGoods.setApiLogId(apiLog.getId());
                if (StringUtils.isNotBlank(apiGoods.getRfidNum())) {
                    if (rfids.contains(apiGoods.getRfidNum())) {
                        newRfids.remove(apiGoods.getRfidNum());
                    }
                }
            }

            //追加新的rfids
            for (String rfid : newRfids) {
                DevApiGoods devApiGoods = new DevApiGoods();
                devApiGoods.setApiLogId(apiLog.getId());
                devApiGoods.setRfidNum(rfid);
                devApiGoods.setUnknownFlag(1);
                devApiGoods.setLeaveFlag(0);
                devApiGoods.setBioCabinetGroupId(cabinetDoor.getCabinetGroupId());
                devApiGoods.setBioCabinetId(cabinetDoor.getCabinetInfoId());
                devApiGoods.setBioCabinetDoorId(cabinetDoor.getId());
                devApiGoods.setCurCabinetGroupId(cabinetDoor.getCabinetGroupId());
                devApiGoods.setCurCabinetId(cabinetDoor.getCabinetInfoId());
                devApiGoods.setCurCabinetDoorId(cabinetDoor.getId());
                goodsList.add(devApiGoods);
            }
            //添加快照
            if (!CollectionUtils.isEmpty(goodsList)) {
                devApiGoodsService.saveBatch(goodsList);
            }
        }
    }

}
